//调用安卓原生方法集合
const main = plus.android.runtimeMainActivity();
const Intent = plus.android.importClass('android.content.Intent');
const Build = plus.android.importClass('android.os.Build');
const Uri = plus.android.importClass('android.net.Uri');
const DocumentsContract = plus.android.importClass('android.provider.DocumentsContract');
const ContentUris = plus.android.importClass('android.content.ContentUris');
const MediaStore = plus.android.importClass('android.provider.MediaStore');
const Environment = plus.android.importClass('android.os.Environment');
const System = plus.android.importClass('java.lang.System');
const File = plus.android.importClass('java.io.File');
const FileInputStream = plus.android.importClass('java.io.FileInputStream')
const FileOutputStream = plus.android.importClass('java.io.FileOutputStream')
const OutputStreamWriter = plus.android.importClass('java.io.OutputStreamWriter')
const BufferedWriter = plus.android.importClass('java.io.BufferedWriter')
const MediaScannerConnection = plus.android.importClass('android.media.MediaScannerConnection')
const Context = plus.android.importClass('android.content.Context');
const URLConnection = plus.android.importClass('java.net.URLConnection');
const MimeTypeMap = plus.android.importClass("android.webkit.MimeTypeMap")
const WallpaperManager = plus.android.importClass("android.app.WallpaperManager")
const BitmapFactory = plus.android.importClass("android.graphics.BitmapFactory")
const resolver = main.getContentResolver()
const rootPath = Environment.getExternalStorageDirectory()
const sdPath = System.getenv("SECONDARY_STORAGE");
const isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;


/**
 * 处理系统文件管理器导出的文件
 * @param {Uri} uri 安卓Uri对象
*/
function handleFile (uri) {
	plus.android.importClass(uri);
	const scheme = uri.getScheme()
	let filePath = ''
	const isDocument = DocumentsContract.isDocumentUri(main, uri)
	const isTreeDocument = DocumentsContract.isTreeUri(uri)
	// DocumentProvider
	if(isKitKat && (isDocument || isTreeDocument)) {
		const authority = uri.getAuthority()
	    // console.log("版本大于 4.4 ");
	    // ExternalStorageProvider
	    if("com.android.externalstorage.documents" == authority) {
	        const docId = isDocument ? DocumentsContract.getDocumentId(uri) : DocumentsContract.getTreeDocumentId(uri);
	        const split = docId.split(":");
	        const type = split[0];
	        if("primary" == type) {
	            filePath = rootPath + "/" + split[1]
	        } else {
	            if(sdPath) filePath = sdPath + "/" + split[1]
	        }
	    }
	    // DownloadsProvider
	    else if("com.android.providers.downloads.documents" == authority) {
	        const docId = isDocument ? DocumentsContract.getDocumentId(uri) : DocumentsContract.getTreeDocumentId(uri);
			const split = docId.split(":");
			filePath = isDocument ? split[1] : rootPath + '/' + split[0]
	        // const contentUri = ContentUris.withAppendedId(
	        //    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
	        // Uri.parse("content://downloads/public_downloads"), id);
	        // filePath = getDataColumn(contentUri, null, null)
	    }
	    // MediaProvider
	    else if("com.android.providers.media.documents" == authority) {
	        const docId = isDocument ? DocumentsContract.getDocumentId(uri) : DocumentsContract.getTreeDocumentId(uri);
	        const split = docId.split(":");
	        const type = split[0];
			let contentUri = ''
	        if("image" == type) {
	        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
	        } else if("video" == type) {
	        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
	        } else if("audio" == type) {
	        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
	        }
	        const selection = "_id=?";
	        const selectionArgs = new Array();
	        selectionArgs[0] = split[1];
	        filePath = getDataColumn(contentUri, selection, selectionArgs)
	    }
	}
	// MediaStore (and general)
	else if("content" == scheme) {
	    filePath = getDataColumn(uri, null, null)
	}
	// File
	else if("file" == scheme) {
	    filePath = uri.getPath()
	}
	const file = new File(filePath)
	const fileSize = isTreeDocument ? '' : new FileInputStream(file)
	const available = isTreeDocument ? '' : fileSize.available()
	const lastModified = file.lastModified()
	return isTreeDocument ? {
		path: filePath,
		name: file.getName(),
		lastModified: lastModified,
		time: dateFormat(lastModified)
	} : {
		path: filePath,
		name: file.getName(),
		type: plus.android.invoke(resolver, "getType",uri) || getFileMimeTypeAndroid(file),
		available: available,
		size: readFileSize(available),
		lastModified: lastModified,
		time: dateFormat(lastModified)
	}
}

/**
 * 根据文件后缀获取MIME类型
 * @param {Uri} file 安卓file对象
*/
function getFileMimeTypeAndroid(file) {
  const fileName = file.getName();
  const extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
  const mimeTypeMap = MimeTypeMap.getSingleton();
  let mimeType = mimeTypeMap.getMimeTypeFromExtension(extension);
  if (!mimeType) mimeType = URLConnection.guessContentTypeFromName(fileName);
  return mimeType || 'application/octet-stream';
}

function getDataColumn(uri, selection, selectionArgs) {
    plus.android.importClass(resolver);
    const cursor = resolver.query(uri, ['_data'], selection, selectionArgs, null);
    plus.android.importClass(cursor);
    if(cursor != null && cursor.moveToFirst()) {
    var column_index = cursor.getColumnIndexOrThrow('_data');
    var result = cursor.getString(column_index)
    cursor.close();
    return result;
    }
    return null;
}

function readFileSize (available) {
	const size = available != 'null' ? available : 0;
	let fileSizeString;
	if(size == 0){
		fileSizeString = "0B";
	}else if(size < 1024){
		fileSizeString = size + "B";
	}else if(size < 1048576){
		fileSizeString = (size/1024).toFixed(2) + "KB";
	}else if (size < 1073741824){
		fileSizeString = (size/1048576).toFixed(2) + "MB";
	}else{
		fileSizeString = (size/1073741824).toFixed(2) + "GB";
	}
	return fileSizeString;
}

function dateFormat (lastModified) {
	const d = new Date(lastModified)
	const year = d.getFullYear()
	const month = d.getMonth() + 1
	const day = d.getDate()
	const hour = d.getHours()
	const seconds = d.getSeconds()
	const minutes = d.getMinutes()
	return year + '年' + month + '月' + day + '日 ' + hour + '时' + seconds + '分' + minutes + '秒'
}

/**
 * 判断是否有权限
 * @param {Array} permissions 权限列表
 * @param {String} message 无权限提示
 * @param {Function} success 成功回调
 * @param {Function} fail 失败回调
*/
const requestPermissions = function ({permissions = [], message = '权限未开启：\n\n点击确认获取权限', success, fail}) {
	plus.android.requestPermissions(permissions,(e) =>{
		if(e.deniedAlways.length>0){//权限被永久拒绝
			uni.showModal({
				content: message,
				success: ret => {
					if ( ret.confirm ) {
						this.requestPermissions({permissions: permissions, message: message, success: success, fail: fail})
					} else {
						fail && fail()
					}
				},
				fail: () => {
					fail && fail()
				}
			})
		}
		if(e.deniedPresent.length>0){//权限被临时拒绝
			uni.showModal({
				content: message,
				success: ret => {
					if ( ret.confirm ) {
						this.requestPermissions({permissions: permissions, message: message, success: success, fail: fail})
					} else {
						fail && fail()
					}
				},
				fail: () => {
					fail && fail()
				}
			})
		}
		//权限被允许
		if(e.granted.length > 0)success && success()
	}, function(e){
	    console.log('Request Permissions error:'+JSON.stringify(e));
	});
}

/**
 * 调用系统分享分享文件
 * @param {String} filePath 文件路径
*/
const shareFile = function (filePath) {
	if ( !filePath ) {
		uni.showToast({
			title: '请传入分享文件路径',
			icon: 'none'
		})
		return
	}
	requestPermissions({
		permissions: ['android.permission.READ_EXTERNAL_STORAGE', 'android.permission.WRITE_EXTERNAL_STORAGE'],
		message: '分享本地文件需要读取和写入存储权限：\n\n点击确认获取权限',
		success: () => {
			const url = plus.io.convertLocalFileSystemURL(filePath)
			const file = new File(url)
			if ( file && file.exists() ) {
				const name = file.getName()
				const fileNameIndex = name.lastIndexOf(".");
				const fileNameLength = name.length;
				const fileFormat = name.substring(fileNameIndex + 1, fileNameLength);
				const fileName = '/' + (new Date().getTime().toString() + Math.round(Math.random() * 10000)) + '.' + fileFormat
				const accept = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileFormat)
				const TempPath = rootPath + '/Download/temp'
				const TempFolder = new File(TempPath)
				const newFilePath = TempPath + fileName
				if ( !TempFolder.exists() ) TempFolder.mkdirs()
				const listener = new plus.android.implements('android.media.MediaScannerConnection$OnScanCompletedListener', {
				    'onScanCompleted': (path, uri) => {  
				        const shareIntent = new Intent()  
				            .setAction(Intent.ACTION_SEND)  
				            .setType(accept || "*/*")  
				            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)  
				            .putExtra(Intent.EXTRA_TEXT, '分享到')  
				            .putExtra(Intent.EXTRA_STREAM, uri) // Uri.parse(file_entry.fullPath))  
				            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
						main.startActivity(Intent.createChooser(shareIntent, '分享到'))
				        new File(path).deleteOnExit()
				    }  
				})
				file.renameTo(new File(newFilePath))
				MediaScannerConnection.scanFile(main, [newFilePath], null, listener)
				// plus.io.resolveLocalFileSystemURL(TempPath, function(entry1) {
				// 	plus.io.resolveLocalFileSystemURL(url, function (entry2) {
				// 		const listener = new plus.android.implements('android.media.MediaScannerConnection$OnScanCompletedListener', {
				// 		    'onScanCompleted': (path, uri) => {  
				// 		        const shareIntent = new Intent()  
				// 		            .setAction(Intent.ACTION_SEND)  
				// 		            .setType(accept || "*/*")  
				// 		            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)  
				// 		            .putExtra(Intent.EXTRA_TEXT, '分享到')  
				// 		            .putExtra(Intent.EXTRA_STREAM, uri) // Uri.parse(file_entry.fullPath))  
				// 		            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
				// 				MainActivity.startActivity(Intent.createChooser(shareIntent, '分享到'))
				// 		        new File(path).deleteOnExit()
				// 		    }  
				// 		})
				// 		MediaScannerConnection.scanFile(MainActivity, [TempPath + fileName], null, listener)
				// 		entry2.copyTo(entry1,fileName,function(res) {
				// 		}, function(e) {
				// 			uni.showToast({
				// 				title: '复制资源失败' + JSON.stringify(e),
				// 				icon: 'none'
				// 			})
				// 		})
				// 	}, function(e) {
				// 		uni.showToast({
				// 			title: '读取资源失败' + JSON.stringify(e),
				// 			icon: 'none'
				// 		})
				// 	})
				// }, function(e) {
				// 	uni.showToast({
				// 		title: '读取系统根目录失败' + JSON.stringify(e),
				// 		icon: 'none'
				// 	})
				// })
			} else {
				uni.showToast({
					title: '获取资源失败',
					icon: 'none'
				})
			}
		},
		fail: () => {
			console.log('fail');
		}
	})
}

/**
 * 开启原生系统文件管理器
 * @param {String} accept 文件类型 不传默认选择文件夹 指定
 * @param {Boolean} multiple 开启多选模式
 * @param {Number} count 最大处理文件数量 不传默认全部
 * @param {Function} success 成功回调
 * @param {Function} fail 失败回调
*/
const openFileSystem = function ({accept = '', multiple, count, success, fail}) {
	const REQUESTCODE = 1;
	const intent = accept ? new Intent(Intent.ACTION_GET_CONTENT) : new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
	if ( accept ) {//选择文件
		//API大于19之后设置多个类型采用以下方式
		const mimeTypes = accept.split('|')
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		if ( multiple ) intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)//允许多选
		if ( mimeTypes.length > 1 && isKitKat ) {//指定多类型文件
			intent.setType(accept)
			intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
		}  else {
			intent.setType(accept)
		}
	} else {//选择文件夹
		intent.addCategory(Intent.CATEGORY_DEFAULT)
	}
	//intent.setType("*/*");//设置类型，任意类型
	//intent.setType("video/*|audio/*");指定多种类型
	//intent.setType("image/*");选择图片
	//intent.setType("audio/*"); //选择音频
	//intent.setType("video/*"); //选择视频 （mp4 3gp 是android支持的视频格式）
	//intent.setType("application/x-mpegURL"); //选择m3u8 
	main.onActivityResult = function(requestCode, resultCode, data) {
	    if (resultCode == -1 && REQUESTCODE == requestCode) {
			try{
				if ( data.getData() != null ) {
					const file = handleFile(data.getData())
					success && success(file)
				} else if ( data.getClipData() != null ) {
					const clipData = data.getClipData()
					plus.android.importClass(clipData);
					const len = count ? Math.min(clipData.getItemCount(), count) : clipData.getItemCount()
					uni.showLoading({
						title: '正在读取选中的' + len + '个文件'
					})
					const files = []
					for ( let i = 0; i < len; i++ ) {
						const clipItem = clipData.getItemAt(i)
						const uri = clipItem.getUri()
						files.push(handleFile(uri))
					}
					uni.hideLoading()
					success && success(files)
				}
			}catch(e){
				fail && fail(e)
			}
	    } else {
			fail && fail('no file selected')
		}
	}
	main.startActivityForResult(intent,REQUESTCODE);
}

/**
 * 设置系统锁屏和壁纸
 * @param {String} type 类型 all-锁屏和壁纸 wallpaper-壁纸 lock-锁屏
 * @param {String} path 图片路径
*/
const setWallpaper = function (type = 'all', path) {
	try {
		const filePath = plus.io.convertLocalFileSystemURL(path)
		const bitmap = BitmapFactory.decodeFile(filePath)
		const wallpaperManager = WallpaperManager.getInstance(main)
		plus.android.importClass(wallpaperManager)
		if ( type == 'all' || type == 'wallpaper' ) wallpaperManager.setBitmap(bitmap) //设置壁纸
		if ( type == 'all' || type == 'lock' ) wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK) //设置锁屏
		plus.android.invoke(bitmap, 'recycle')
		uni.showToast({
			title: "壁纸设置成功",
			icon: "none"
		})
	} catch (e) {
		uni.showToast({
			title: "壁纸设置失败",
			icon: "none"
		})
	}
}

/**
 * 卸载应用
 * @param {String} packagename 应用包名
*/
const uninstall = function (packagename) {
	const uri = Uri.fromParts('package', packagename, null)
	const intent = new Intent(Intent.ACTION_DELETE, uri)
	main.startActivity(intent)
}

/**
 * 写入文档内容
 * @param {String} filePath 文件路径
 * @param {String} content 内容
 * @param {String} charset 字符编码
 * @param {Function} success 成功回调
 * @param {Function} fail 失败回调
*/
const writeDocumentContent = function ({filePath, content, charset, success, fail}) {
	const file = new File(filePath)
	if ( file != null && file.exists() ) {
		try{
			file.createNewFile()
			const fileOutputStream = new FileOutputStream(file)
			const outputStreamWriter = new OutputStreamWriter(fileOutputStream, charset || 'GB2312')
			const bufferedWriter = new BufferedWriter(outputStreamWriter)
			bufferedWriter.write(content)
			bufferedWriter.close()
			const fileSize = new FileInputStream(file)
			const available = fileSize.available()
			const size = readFileSize(available)
			success && success({
				available: available,
				size: size
			})
		}catch(e){
			fail && fail(e)
		}
	} else {
		fail && fail({
			message: '文件不存在或者不能被操作'
		})
	}
}

/**
 * 下载网络图片存入本地访问
 * @param {String} src 网络图片路径
 * @param {Array} referer referer
 * @param {Function} success 成功回调
 * @param {Function} fail 失败回调
*/
const downloadImageSaveLocal = function ({src, referer, success, fail, complete}) {
	const suffix = 'SELECT_REFERER_IMAGE'
	const caches = uni.getStorageSync(suffix) || []
	const index = caches.findIndex(cache => cache.origin == src)
	if ( index > -1 ) {
		const file = new File(plus.io.convertLocalFileSystemURL(caches[index].path))
		if ( file != null && file.exists() ) {
			success && success(caches[index].path)
			complete && complete(caches[index].path)
			return
		} else {
			caches.splice(index, 1)
			uni.setStorageSync(suffix, caches)
		}
	}
	uni.downloadFile({
		header: {
			Referer: referer || src
		},
		url: src,
		success: res => {
			if (res.statusCode === 200) {
				caches.push({
					origin: src,
					path: res.tempFilePath
				})
				uni.setStorageSync(suffix, caches)
				success && success(res.tempFilePath)
				complete && complete(res.tempFilePath)
			} else {
				fail && fail(src)
				complete(src)
			}
		},
		fail: err => {
			fail && fail(src)
			complete(src)
		}
	})
}

/**
 * 设置全屏
 * @param {String} bol 布尔值
*/
const setFullscreen = function (bol) {
	plus.navigator.setFullscreen(bol);
}

/**
 * 写入并导出文件
 * @param {String} fileName 导出文件名称
 * @param {Array} content 写入文件内容
 * @param {Function} success 成功回调
 * @param {Function} fail 失败回调
*/
const writeAndExportFile = function ({fileName, content, success, fail}) {
	plus.io.requestFileSystem(plus.io.PRIVATE_DOC, ( fs ) => {
		let file = plus.android.newObject("java.io.File", fs.root.fullPath + fileName);
		plus.android.invoke(file, 'createNewFile')
		let fileOutputStream = plus.android.newObject("java.io.FileOutputStream", file);
		let outputStreamWriter = plus.android.newObject("java.io.OutputStreamWriter", fileOutputStream, "utf-8");
		let bufferedWriter = plus.android.newObject("java.io.BufferedWriter", outputStreamWriter);
		plus.android.invoke(bufferedWriter, 'write', content)
		plus.android.invoke(bufferedWriter, 'close')
		success && success({
			fileName: plus.android.invoke(file, 'getName'),
			root: fs.root.fullPath
		})
	}, ( e ) => {
		fail && fail(e)
	});
}

module.exports = {
	shareFile,
	openFileSystem,
	setWallpaper,
	requestPermissions,
	uninstall,
	writeDocumentContent,
	setFullscreen,
	downloadImageSaveLocal,
	writeAndExportFile
}